$(function() {
 
    var url='controls/lg_model.php';
	
	var remember = $.cookie('remember');
	if ( remember == 'true' ) {
		name.val($.cookie('username'));
	}
	
	$("#l_form").validate({
			 
			highlight: function(element) {
				$(element).closest('.elVal').addClass("form-field error");
				$('label[for=message]').hide();
			},
			unhighlight: function(element) {
				$(element).closest('.elVal').removeClass("form-field error");
			},
			rules: {
				username: "required",
				password: "required"
			},
		
			messages: {
				username: "กรุณากรอก Username",
				password: "กรุณากรอก Password"
			},
			errorPlacement: function(error, element) {
				error.appendTo( element.closest(".elVal") );
				$('label[for=message]').hide();
			},
			submitHandler: function(form) {
				$('label[for=message]').hide();
				$.ajax({
					type: 'POST',
					cache: false,
					url: url,
					data: {"m": "login", "u": $("#username").val(),"p":$("#password").val()},
					success: function(data) {
						 
						var obj=eval("(" + data + ")");
						
						if(obj['result']==1){
							if ($('#remember').attr('checked')) {
								var username = name.val();
								// set cookies to expire in 256 days
								$.cookie('username', username, { expires: 256 });
								$.cookie('remember', true, { expires: 256 });
							} else {
									// reset cookies
								$.cookie('username', null);
								$.cookie('remember', null);
							}
							
							form.submit();
						}else{
							  $("#username,#password").closest('.elVal').addClass("form-field error");
							  
							 $('label[for=message]').show().addClass('error').html('Username หรือ Password ไม่ถูกต้อง');
							  
						}
						
					}
				});
			}
		});

    
});


